package com.android.djlmapp.http;

import android.app.Activity;
import android.util.Log;

import com.android.djlmapp.model.home.Info;
import com.android.djlmapp.token.TokenExpiredUtils;
import com.android.djlmapp.tools.global.MyActivityManager;
import com.android.djlmapp.tools.global.UserInfoUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.request.base.Request;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;

/**
 * Created by yucheng on 2018/3/27.
 */

public class HttpManage {
    /**
     * 请求回调
     */
    private AbsCallback<String> mCallBack;
    /**
     * 正常请求参数集合
     */
    private HashMap<String, String> mParamMap;
    /**
     * 请求路径
     */

    private String mRequestUrl;
    /**
     * 上传文件的集合
     */
    private HashMap<String, File> mFileRequestMap;
    /**
     * 是否是包含文件的请求
     */
    private boolean isFileRequest = false;

    /**
     * 字符串请求
     *
     * @param stringParams
     * @param callBack
     * @param url
     */
    public void postStringRequest(HashMap<String, String> stringParams, AbsCallback<String> callBack, String url) {
        mCallBack = callBack;
        mParamMap = stringParams;
        mRequestUrl = url;
        isFileRequest = false;

        String token = UserInfoUtils.getUserInfoUtilsInstance().getToken();
        String version = UserInfoUtils.getUserInfoUtilsInstance().getVersion();
        mParamMap.put("token", token);
        mParamMap.put("version", version);
        String signStr = new ComPareUtils.ComPareBuilder().putMap(mParamMap).create().getSignString();
        mParamMap.put("sign", signStr);

        PostRequest<String> post = OkGo.post(url);
        Collection<String> keyset = mParamMap.keySet();
        List<String> list = new ArrayList<String>(keyset);
        //对key键值按字典升序排序
        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
            // 拼接键值对
            post.params(list.get(i), mParamMap.get(list.get(i)));
        }
        HttpParams params = post.getParams();
        String str = params.toString();
        Log.e("项目异常", "------post请求参数------" + str);
        post.execute(mStringCallback);
    }

    /**
     * 文件请求
     *
     * @param stringParams
     * @param fileParams
     * @param callBack
     * @param url
     */
    public void postFileRequest(HashMap<String, String> stringParams, HashMap<String, File> fileParams,
                                AbsCallback<String> callBack, String url) {
        mCallBack = callBack;
        mParamMap = stringParams;
        mFileRequestMap = fileParams;
        mRequestUrl = url;
        isFileRequest = true;

        String token = UserInfoUtils.getUserInfoUtilsInstance().getToken();
        String version = UserInfoUtils.getUserInfoUtilsInstance().getVersion();
        mParamMap.put("token", token);
        mParamMap.put("version", version);
        String signStr = new ComPareUtils.ComPareBuilder().putMap(mParamMap).create().getSignString();
        mParamMap.put("sign", signStr);

        PostRequest<String> post = OkGo.post(url);

        Collection<String> keyset = mParamMap.keySet();
        List<String> list = new ArrayList<String>(keyset);
        //对key键值按字典升序排序
        Collections.sort(list);
        for (int i = 0; i < list.size(); i++) {
            // 拼接键值对
            post.params(list.get(i), mParamMap.get(list.get(i)));
            Log.e("项目异常", "------key------" + list.get(i));
            Log.e("项目异常", "------mParams.get(key)------" + mParamMap.get(list.get(i)));
        }
        for (String fileKey : fileParams.keySet()) {
            post.params(fileKey, fileParams.get(fileKey));
        }
        post.execute(mStringCallback);
    }

    private StringCallback mStringCallback = new StringCallback() {
        @Override
        public void onStart(Request<String, ? extends Request> request) {
            super.onStart(request);
        }

        @Override
        public void onCacheSuccess(Response<String> response) {
            super.onCacheSuccess(response);

        }

        @Override
        public void onSuccess(Response<String> response) {
            try {
                String body = response.body();
                Log.e("项目异常HttpManage", "------HttpManage------" + body);
                if (response.body().contains("code")) {
                    Gson gson = new Gson();
                    Info info = gson.fromJson(body, Info.class);
                    if (info.getCode() == 1111) {
                        Stack<Activity> stack = MyActivityManager.mActivites;
                        if (stack != null && stack.size() > 0) {
                            Activity activity = stack.lastElement();
                            new TokenExpiredUtils(activity
                                    , new TokenExpiredUtils.RefreshTokenListener() {
                                @Override
                                public void refreshTokenSuc(String token) {
                                    UserInfoUtils.getUserInfoUtilsInstance().setToken(token); // 更新token
                                    mParamMap.put("token", token); // 更新token
                                    if (isFileRequest) {
                                        // 文件请求
                                        postFileRequest(mParamMap, mFileRequestMap, mCallBack, mRequestUrl);
                                    } else {
                                        Log.e("HttpManage", "------字符串请求------");
                                        // 字符串请求
                                        postStringRequest(mParamMap, mCallBack, mRequestUrl);
                                    }
                                }
                            }).refreshServ();
                        }
                    } else {
                        mCallBack.onSuccess(response);
                    }
                } else {
                    mCallBack.onSuccess(response);
                }
            } catch (Exception e) {
                Log.e("HttpManage", "------数据解析异常------" + e.toString());
                Response<String> stringResponse = new Response<>();
                stringResponse.setBody("数据解析异常");
                mCallBack.onSuccess(stringResponse);
            }
        }

        @Override
        public void onError(Response<String> response) {
            super.onError(response);
            Log.e("HttpManage", "------onError------" + response.getException());
            mCallBack.onError(response);
        }

        @Override
        public void onFinish() {
            mCallBack.onFinish();
        }
    };
}
